import { setSession, getSession } from "../utils";
import { post } from "../utils/request";
export default {
  namespaced: true,
  state: {
    //仓库数据作持久化的操作
    isLogin: getSession("isLogin") || false,
    nameList: getSession("list") || [],
    token: getSession("token") || "",
    id: getSession("id") || "",
  },
  mutations: {
    addItem(state, payload) {
      state.nameList.push(payload);
      setSession("list", state.nameList);
    },
    changeIsLogin(state, payload) {
      state.isLogin = payload;
      sessionStorage.setItem("isLogin", state.isLogin);
    },
    changeToken(state, payload) {
      state.token = payload;
      setSession("token", state.token);
    },
    getId(state, payload) {
      state.id = payload;
      setSession("id", state.id);
    },
  },
  actions: {
    //异步操作 vuex 上下文 指的是 vuex commit
    changeIsLogin({ commit }, payload) {
      return new Promise((resolve, reject) => {
        post("/login", payload).then(
          (res) => {
            resolve(res);
            console.log(res);
            commit("changeIsLogin", true);
            commit("changeToken", res.data.result.token);
          },
          (err) => {
            reject(err);
          }
        );
      });
    },
  },
};
